<template>
  <div class="movie-carousel">
    <h3 class="section-title">热门电影推荐</h3>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p class="loading-text">正在加载热门电影...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <div class="error-icon">❌</div>
      <p class="error-text">加载电影数据失败</p>
      <button class="retry-button" @click="fetchMovies">重新加载</button>
    </div>

    <!-- 轮播图 -->
    <el-carousel
        v-else
        :interval="5000"
        height="400px"
        indicator-position="outside"
        arrow="always"
    >
      <el-carousel-item v-for="(movie, index) in carouselItems" :key="index">
        <img :src="movie.poster" class="carousel-image" />
        <div class="carousel-overlay">
          <h2 class="movie-title">{{ movie.title }}</h2>

          <div class="movie-info">
            <div class="info-item">
              <el-icon><Clock /></el-icon> {{ movie.duration }}分钟
            </div>
            <div class="info-item">
              <el-icon><Film /></el-icon> {{ movie.genre }}
            </div>
            <div class="info-item">
              <el-icon><Tickets /></el-icon> {{ movie.cinema }}
            </div>
          </div>

          <p class="movie-description">
            {{ getMovieDescription(movie.title) }}
          </p>

          <div class="action-buttons">
            <el-button type="primary" size="large" round @click="showBuyDialog(movie)">
              <el-icon><VideoPlay /></el-icon> 立即购票
            </el-button>
            <el-button type="info" size="large" round>
              <el-icon><InfoFilled /></el-icon> 查看详情
            </el-button>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>

    <div class="stats-bar">
      <div class="stat-item">
        <el-icon><Film /></el-icon> 当前展示: <span class="stat-value">{{ carouselItems.length }}</span> 部电影
      </div>
      <div class="stat-item">
        <el-icon><Clock /></el-icon> 自动切换: <span class="stat-value">5</span> 秒
      </div>
      <div class="stat-item">
        <el-icon><Refresh /></el-icon> 最后更新: <span class="stat-value">{{ lastUpdated }}</span>
      </div>
    </div>

    <!-- 购买确认对话框 -->
    <el-dialog
        v-model="buyDialogVisible"
        title="确认购买"
        width="30%"
        center
        :before-close="handleDialogClose"
    >
      <div class="dialog-content">
        <p>你确定要购买《{{ selectedMovie.title }}》电影票吗？</p>
        <p>影院: {{ selectedMovie.cinema }}</p>
        <p>场次: {{ selectedMovie.date }} {{ selectedMovie.time }}</p>
        <p>时长: {{ selectedMovie.duration }}分钟</p>
        <p>类型: {{ selectedMovie.genre }}</p>
        <p class="price-info">
          原价: <span class="original-price">¥{{ selectedMovie.price }}</span>
          <span v-if="selectedMovie.discount"> 折扣: -¥{{ selectedMovie.discount }}</span>
          <span class="final-price"> 实付: ¥{{ (selectedMovie.price - (selectedMovie.discount || 0)).toFixed(2) }}</span>
        </p>
        <p>剩余票数: {{ selectedMovie.amount }} 张</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="confirmBuyTicket">确认购买</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import {
  Clock, Film, Tickets, VideoPlay, InfoFilled, Refresh
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import movieService from '@/services/movie'

const carouselItems = ref([])
const loading = ref(true)
const error = ref(false)
const lastUpdated = ref('')
const buyDialogVisible = ref(false)
const selectedMovie = ref({})

// 电影描述映射
const movieDescriptions = {
  '流浪地球2': '太阳即将毁灭，人类在地球表面建造出巨大的推进器，寻找新家园。然而宇宙之路危机四伏，为了拯救地球，流浪地球时代的年轻人再次挺身而出，展开争分夺秒的生死之战。',
  '满江红': '南宋绍兴年间，岳飞死后四年，秦桧率兵与金国会谈。会谈前夜，金国使者死在宰相驻地，所携密信也不翼而飞。一个小兵与亲兵营副统领机缘巧合被裹挟进这巨大阴谋之中。',
  '复仇者联盟4：终局之战': '宇宙由于灭霸的行动而变得满目疮痍，在泰坦星与灭霸决战失败的托尼·斯塔克流落在茫茫宇宙之中。在存活希望渺茫之际，惊奇队长解救了托尼，复仇者联盟重新集结，逆转灭霸的所作所为，彻底恢复宇宙的秩序。',
  '哪吒之魔童降世': '天地灵气孕育出一颗能量巨大的混元珠，元始天尊将混元珠提炼成灵珠和魔丸，灵珠投胎为人，助周伐纣时可堪大用；而魔丸则会诞出魔王，为祸人间。元始天尊启动了天劫咒语，3年后天雷将会降临，摧毁魔丸。',
  '泰坦尼克号': '1912年4月10日，泰坦尼克号从英国南安普顿出发，计划驶往美国纽约。富家少女罗丝与母亲及未婚夫卡尔坐上了头等舱；另一边，放荡不羁的少年画家杰克也在码头的一场赌博中赢得了下等舱的船票。'
}

// 获取电影描述
const getMovieDescription = (title) => {
  return movieDescriptions[title] || '一部精彩绝伦的电影作品，不容错过！'
}

// 格式化当前时间
const formatTime = () => {
  const now = new Date()
  return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
}

// 从后端获取电影数据
const fetchMovies = async () => {
  try {
    loading.value = true
    error.value = false

    // 从后端获取实际数据
    const response = await axios.get('http://localhost:9999/api/movies/tickets', {
      params: { page: 1, size: 4 },
      headers: {
        Authorization: `Bearer ${localStorage.getItem('auth_token')}`
      }
    })

    // 检查响应状态和业务状态码
    if (response.status === 200 && response.data.code === 200) {
      // 正确解析嵌套的数据结构
      if (response.data.data && response.data.data.list) {
        carouselItems.value = response.data.data.list
        lastUpdated.value = formatTime()
      } else {
        throw new Error('返回数据结构异常')
      }
    } else {
      throw new Error(`API错误: ${response.data.message || '未知错误'}`)
    }
  } catch (err) {
    console.error('API请求错误:', err)
    error.value = true

    // 显示更友好的错误信息
    if (err.response && err.response.data && err.response.data.message) {
      ElMessage.error(err.response.data.message)
    } else {
      ElMessage.error('获取电影数据失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 显示购买对话框
const showBuyDialog = (movie) => {
  selectedMovie.value = { ...movie }
  buyDialogVisible.value = true
}

// 关闭购买对话框
const handleDialogClose = () => {
  buyDialogVisible.value = false
}

// 确认购买
const confirmBuyTicket = () => {
  if (!selectedMovie.value ||!selectedMovie.value.id) return

  movieService.buyTicket(selectedMovie.value.id)
      .then(response => {
        ElMessage.success('购买成功！请前往订单页面查看')
        buyDialogVisible.value = false
      })
      .catch(error => {
        console.error('购买失败:', error)
        ElMessage.error(error.response?.data?.message || '购买失败，请稍后再试')
      })
}

onMounted(() => {
  fetchMovies()
})
</script>
<style scoped>
.movie-carousel {
  margin-bottom: 40px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 20px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.section-title {
  text-align: center;
  font-size: 1.8rem;
  margin-bottom: 20px;
  color: #fff;
  text-shadow: 0 0 10px rgba(0, 195, 255, 0.7);
  position: relative;
  padding-bottom: 15px;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 3px;
  background: linear-gradient(90deg, transparent, #00c3ff, transparent);
  border-radius: 2px;
}

.carousel-wrapper {
  position: relative;
  border-radius: 15px;
  overflow: hidden;
}

.carousel-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.carousel-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.9));
  color: white;
  padding: 20px;
  border-radius: 0 0 15px 15px;
}

.movie-title {
  font-size: 1.8rem;
  margin-bottom: 10px;
  color: #fff;
  text-shadow: 0 0 8px rgba(0, 195, 255, 0.7);
}

.movie-info {
  display: flex;
  gap: 15px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.info-item {
  display: flex;
  align-items: center;
  background: rgba(0, 195, 255, 0.2);
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.85rem;
}

.info-item i {
  margin-right: 5px;
  color: #00c3ff;
}

.movie-description {
  margin-bottom: 15px;
  font-size: 1rem;
  line-height: 1.5;
  max-width: 800px;
  color: #e0e0e0;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 15px;
}

.loading-container, .error-container {
  height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(30, 30, 50, 0.7);
  border-radius: 15px;
}

.loading-spinner {
  width: 60px;
  height: 60px;
  border: 6px solid rgba(0, 195, 255, 0.3);
  border-top: 6px solid #00c3ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text, .error-text {
  font-size: 1.2rem;
  color: #00c3ff;
  text-align: center;
}

.error-icon {
  font-size: 3rem;
  color: #ff4d4f;
  margin-bottom: 15px;
}

.retry-button {
  margin-top: 15px;
  padding: 8px 20px;
  font-size: 1rem;
  background: linear-gradient(135deg, #00c3ff, #0077ff);
  border: none;
  border-radius: 25px;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 119, 255, 0.4);
}

.retry-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 18px rgba(0, 119, 255, 0.6);
}

.stats-bar {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  padding: 12px 15px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  font-size: 0.85rem;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-item i {
  margin-right: 6px;
  color: #00c3ff;
}

.stat-value {
  font-weight: bold;
  color: #00c3ff;
  margin-left: 4px;
}

@media (max-width: 768px) {
  .carousel-image {
    height: 350px;
  }

  .movie-title {
    font-size: 1.5rem;
  }

  .section-title {
    font-size: 1.6rem;
  }

  .movie-info {
    gap: 10px;
  }

  .loading-container, .error-container {
    height: 350px;
  }

  .stats-bar {
    flex-direction: column;
    gap: 8px;
    align-items: center;
  }
}

@media (max-width: 480px) {
  .carousel-image {
    height: 300px;
  }

  .movie-title {
    font-size: 1.3rem;
  }

  .section-title {
    font-size: 1.4rem;
  }

  .carousel-overlay {
    padding: 15px 12px;
  }

  .movie-info {
    flex-direction: column;
    gap: 8px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 10px;
  }

  .loading-container, .error-container {
    height: 300px;
  }
}
</style>